package cn.mugutu.finance.service.system.impl;

import cn.mugutu.finance.query.BaseQuery;
import cn.mugutu.finance.service.system.BaseService;
import cn.mugutu.finance.utils.Pager;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

@Service
@SuppressWarnings("all")
public abstract class BaseServiceImpl<T> implements BaseService<T> {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseServiceImpl.class);

    @Autowired
    protected SessionFactory sf;

    protected Class<T> clazz;

    public BaseServiceImpl() {
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType ptype = (ParameterizedType) type;
            clazz = (Class<T>) ptype.getActualTypeArguments()[0];
            LOGGER.info("项目启动初始化,entityClass===>{}", clazz);
        }
    }

    public Session getSession() {
        return sf.getCurrentSession();
    }

    public void save(T t) {
        getSession().save(t);
    }

    @Override
    public void saveOrUpdate(T t) {
        getSession().saveOrUpdate(t);
    }

    public void delete(Serializable id) {
        T t = get(id);
        if (t != null) {
            getSession().delete(t);
        }
    }

    @Override
    public void deleteAll() {
        getSession().createQuery("DELETE " + clazz.getName()).executeUpdate();
    }

    public void update(T t) {
        getSession().update(t);
    }

    public T get(Serializable id) {
        return (T) getSession().get(clazz, id);
    }

    public List<T> getAll() {
        return getSession().createQuery("FROM " + clazz.getName()).list();
    }

    public List findByHql(String hql, Object... params) {
        Query query = getSession().createQuery(hql);
        if (params == null) {
            return null;
        }
        int index = 0;
        if (params != null) {
            for (Object o : params) {
                query.setParameter(index++, o);
            }
        }
        return query.list();
    }

    public Object getUniqueResult(String hql, Object... params) {
        Query query = getSession().createQuery(hql);
        int index = 0;
        if (params != null) {
            for (Object o : params) {
                query.setParameter(index++, o);
            }
        }
        return query.uniqueResult();
    }


    public List<T> findAll() {
        return getSession().createQuery("FROM " + clazz.getName()).list();
    }

    @Override
    public Pager<T> findByPage(BaseQuery baseQuery) {
        String countHql = baseQuery.getCountHql();
        String hql = baseQuery.getHql();

        System.out.println("hql===>" + hql);
        System.out.println("countHql===>" + countHql);
        System.out.println("paramsList===>" + baseQuery.getParamsList());

        Query countQuery = getSession().createQuery(countHql);
        Long totalCount = (Long) buildParams(countQuery, baseQuery).uniqueResult();
        if (totalCount == 0) {
            new Pager<T>();
        }

        Pager<T> pageResult = new Pager(baseQuery.getPageSize(), baseQuery.getCurrentPage(), totalCount.intValue());
        int start = (pageResult.getCurrentPage() - 1) * pageResult.getPageSize();
        Query rowsQuery = getSession().createQuery(hql);
        List list = buildParams(rowsQuery, baseQuery).setFirstResult(start).setMaxResults(pageResult.getPageSize()).list();
        pageResult.setRows(list);
        return pageResult;
    }

    //构建hibernate查询参数
    public Query buildParams(Query query, BaseQuery baseQuery) {
        int index = 0;
        for (Object param : baseQuery.getParamsList()) {
            query.setParameter(index++, param);
        }
        return query;
    }

    //构建hibernate查询参数
    public Query buildParams(Query query, Object... params) {
        int index = 0;
        for (Object param : params) {
            query.setParameter(index++, param);
        }
        return query;
    }

    @Override
    public Pager<T> findByPage(String hql, int currentPage, int pageSize, Object... params) {
        //查询总记录数结果集
        Query countQuery = getSession().createQuery(hql);
        buildParams(countQuery, params);
        List totalCountList = countQuery.list();
        Pager<T> pager = new Pager<>(pageSize, currentPage, totalCountList.size());
        if (totalCountList.size() == 0) {
            return pager;
        }

        //查询展示数据结果集
        Query query = getSession().createQuery(hql);
        buildParams(query, params);
        List result = query.
                setFirstResult((pager.getCurrentPage() - 1) * pager.getPageSize()).
                setMaxResults(pageSize).list();

        pager.setRows(result);
        return pager;
    }
}
